package com.igeek.ssm.config;

import com.github.pagehelper.PageInterceptor;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.util.Properties;

/**
 * @Description MyBatis配置类
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/1/12 14:43
 *
 * 取代MyBatis的核心配置文件SqlMapConfig.xml
 */
//加载外部属性文件
@PropertySource("classpath:db.properties")
//Mapper接口的扫描包，为其生成代理对象，且注册至IOC容器
@MapperScan("com.igeek.ssm.mapper")
public class MyBatisConfig {

    //配置数据源的实例Bean
    @Bean
    public DataSource dataSource(
            @Value("${db.user}") String username,
            @Value("${db.password}") String password,
            @Value("${db.url}") String url,
            @Value("${db.driverClass}") String driverClass
    ) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(url);
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }

    //配置会话工厂实例Bean
    @Bean
    public SqlSessionFactoryBean factory(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        //设置数据源
        factory.setDataSource(dataSource);
        //设置别称
        factory.setTypeAliasesPackage("com.igeek.ssm.pojo");

        //设置全局参数
        Configuration configuration = new Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        factory.setConfiguration(configuration);

        //配置XxxMapper.xml的路径
        factory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*.xml"));

        //分页插件
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        //指定数据库方言
        properties.put("helperDialect","mysql");
        //分页合理化
        properties.put("reasonable","true");
        //配置分页插件的参数
        pageInterceptor.setProperties(properties);
        //会话工厂，设置分页插件
        factory.setPlugins(new Interceptor[]{pageInterceptor});

        return factory;
    }


    //事务

}
